// import logo from './logo.svg';
import { useState, useRef, useEffect } from 'react';
import { Layout, Modal, Popover, message } from 'antd';
import { Button, Dropdown, Space, Divider } from 'antd';

import 'antd/dist/reset.css';
import '../report/App.css';

import LuckyExcel from 'luckyexcel'
import Luckysheet from 'src/component/Luckysheet'
import ReportTree from 'src/component/ReportTree'
import SettingDialog from 'src/component/SettingDialog'

import SparkChannel, { EE } from 'src/ipc/sparkchannel'
import { ReportFile, ReportType } from 'src/core/common'
import { SheetUtil, MyModal } from 'src/util/utils'

const { Header, Content, Sider } = Layout;

function App() {
  const worksheet = useRef(null);
  const fileInputRef = useRef(null);
  const [report, setReport] = useState(null);
  const [content, setContent] = useState(null);
  const [changed, setChanged] = useState(false);
  const [settingDialogOpen, setSettingDialogOpen] = useState(false);
  const [signalDebug, setSignalDebug] = useState(null);

  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      SparkChannel().then(channel => {
        const { signalDebug } = channel;
        setSignalDebug(signalDebug);
      });
    }
  }, []);

  useEffect(() => {
    async function onReportOpen(newReport) {
      try {
        if (report && report.id === newReport.id) {
          return;
        }
        const newContent = await ReportFile.readContent(newReport);
        console.log('openWorkbook', newReport, newContent);

        const setState = () => {
          setReport(newReport);
          setContent(newContent);
          setChanged(false);
        };

        if (changed) {
          MyModal.confirm({
            content: `"${report.report_name}"文件已经被修改，要保存吗`,
            okText: '保存',
            cancelText: '取消',
            onOk: () => {
              saveWorkbook().then(() => {
                setState();
              });
            },
            onCancel: () => {
              setState();
            }
          });

        } else {
          setState();
        }

      } catch (err) {
        console.log('open lxls fail', err);
        message.error('读取文件失败');
      }
    }
    EE.on('open-workbook', onReportOpen);

    // Specify how to clean up after this effect:
    return function cleanup() {
      EE.removeListener('open-workbook', onReportOpen);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    async function onReportDelete(deletedReport) {
      if (report && report.id === deletedReport.id) {
        setReport(null);
        setContent(null);
        setChanged(false);
      }
    }
    EE.on('delete-workbook', onReportDelete);

    return function cleanup() {
      EE.removeListener('delete-workbook', onReportDelete);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function checkWorkbookExist() {
    if (!report) {
      MyModal.warning({ zIndex: 1020, content: '请选择文件打开' });
      return false;
    }
    return true;
  }


  const exportTemplate = () => {
    if (!checkWorkbookExist()) {
      return;
    }
    worksheet.current.exportTemplate();
  };
  const importTemplate = () => {
    if (!checkWorkbookExist()) {
      return;
    }
    fileInputRef.current.value = '';
    fileInputRef.current.click();
  }
  const uploadExcel = (evt) => {
    const files = evt.target.files;
    if (files === null || files.length === 0) {
      console.log("No files wait for import");
      return;
    }

    let name = files[0].name;
    let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length - 1];
    if (suffix !== "xlsx") {
      alert("Currently only supports the import of xlsx files");
      return;
    }

    LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {

      if (exportJson.sheets === null || exportJson.sheets.length === 0) {
        alert("Failed to read the content of the excel file, currently does not support xls files!");
        return;
      }

      const config = worksheet.current.importTemplate({
        data: exportJson.sheets,
        title: report.report_name,
        userInfo: exportJson.info.name.creator
      });
      delete config.book_type; // book_type不可修改

      setContent((origin) => {
        Object.assign(origin.config, config);
        return origin;
      });
      setChanged(true);
    });
  }
  const saveWorkbook = () => {
    if (!checkWorkbookExist()) {
      return;
    }

    const sheets = SheetUtil.getLuckysheetData();
    const newContent = JSON.stringify({ "data": sheets, "config": content.config });
    return ReportFile.writeContent(report, newContent).then(resp => {
      // console.log('save success');
      message.success('保存成功');
      setChanged(false);
    });
  }

  const saveSetting = async (config, autoGenerateConfig) => {
    console.log('saveSetting', config);

    try {
      const newContent = { "data": content.data, "config": config };
      await ReportFile.writeContent(report, JSON.stringify(newContent));
      let newReport;
      if (autoGenerateConfig) {
        const channel = await SparkChannel();
        newReport = { ...report, ...autoGenerateConfig };
        await channel.request_update_report(newReport);
      }

      setSettingDialogOpen(false);
      setContent(newContent);
      if (autoGenerateConfig) {
        setReport(newReport);
      }

    } catch (err) {
      message.error('保存失败');
    }
  }
  const editSetting = () => {
    if (!checkWorkbookExist()) {
      return;
    }
    setSettingDialogOpen(true);
  }
  const insertEnvFill = () => {
    if (!checkWorkbookExist()) {
      return;
    }
    worksheet.current.insertEnvFill();
  }
  const insertRealFill = () => {
    if (!checkWorkbookExist()) {
      return;
    }
    worksheet.current.insertRealFill();
  }
  const insertSeqFill = () => {
    if (!checkWorkbookExist()) {
      return;
    }
    worksheet.current.insertSeqFill();
  }

  let fillButton;
  const itemEnvFill = { key: 'ENV', label: '变量填充', };
  const onMenuClick = (e) => {
    if (e.key === 'ENV') {
      insertEnvFill();
    } else if (e.key === 'REAL') {
      insertRealFill();
    }
  };
  if (report && ReportType.getReportTypeValue(report.report_type) === 'REAL') {
    const items = [itemEnvFill];
    fillButton = (
      <Dropdown.Button
        onClick={insertRealFill}
        menu={{
          items,
          onClick: onMenuClick,
        }}
      >
        实时填充
      </Dropdown.Button>
    )
  } else {
    const items = [
      {
        key: 'REAL',
        label: '实时填充',
      },
      itemEnvFill
    ];
    fillButton = (
      <Dropdown.Button
        onClick={insertSeqFill}
        menu={{
          items,
          onClick: onMenuClick,
        }}
      >
        序列填充
      </Dropdown.Button>
    )
  }

  return (
    <Layout>
      <Header>
        <Space>
          <Button onClick={saveWorkbook}>保存</Button>
          <Button onClick={importTemplate}>导入</Button>
          <input ref={fileInputRef} style={{ display: 'none' }} type="file" onChange={uploadExcel} />
          <Button onClick={exportTemplate}>导出</Button>
          <Divider type="vertical" />
          <Button onClick={editSetting}>模板配置</Button>
          <Divider type="vertical" />
          {fillButton}

          {/* <Upload onChange={uploadExcel}>
            <Button icon={<UploadOutlined />}>Import XLS</Button>
          </Upload> */}
          {signalDebug}
        </Space>
      </Header>
      <Layout>
        <Sider className='report-tree-wrapper'>
          <ReportTree edit={true} />
        </Sider>
        <Content>
          <Luckysheet
            ref={worksheet}
            report={report}
            content={content}
            onChange={() => setChanged(true)} />
        </Content>
      </Layout>

      {settingDialogOpen &&
        <SettingDialog
          report={report}
          config={content && content.config}
          open={settingDialogOpen}
          onCancel={() => setSettingDialogOpen(false)}
          onSubmit={saveSetting} />}

      {/* Fix: 解决在QWebEngineView中Modal静态方法弹出框位置定位错误的问题 */}
      <Modal title="" open={false} />
      {/* Fix: 添加一个Popover，可以解决在QWebEngineView中Popover位置定位错误的问题 */}
      <Popover title="">
        <div />
      </Popover>

    </Layout>

    // <div className="App">
    //   <header className="App-header">
    //   </header>
    // </div>
  );
}

export default App;
